<!-- <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="Canvas Clock - Canvas API Tutorial"/>

    <title>Canvas Clock - Canvas API Tutorial</title>

    <link rel="stylesheet" type="text/css" href="css/style.css"/>
    <script src="js/main_orange.js"></script>
</head>

<body style="width: 100%;">
  <div id="display" style="width: 100%; height: 2000px; background: pink;"></div>
</body>
</html> -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0"
    />
    <meta
      name="description"
      content="Tizen basic template generated by Tizen Web IDE"
    />

    <title>Tizen Web IDE - Tizen - Samsung Tizen TV basic Application</title>

    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <script src="js/main.js"></script>

    <!-- 引入React -->
    <script crossorigin src="lib/react.development.js"></script>
    <!-- 引入ReactDOM -->
    <script crossorigin src="lib/react-dom.development.js"></script>
    <!-- 引入Babel（如果你需要转换JSX） -->
    <script src="lib/standalone/babel.min.js"></script>

    <script src="lib/dayjs.min.js"></script>
    <link rel="stylesheet" type="text/css" href="css/reset.css" />
    <script src="lib/antd.min.js"></script>

    <script src="lib/babel.min.js"></script>

    <script src="lib/ahooks.js"></script>
  </head>

  <body>
    <div id="root"></div>
    <script type="text/babel" data-plugins="transform-modules-umd">
      import {
        Button,
        Segmented,
        Switch,
        ConfigProvider,
        notification,
        Input,
        message,
      } from "antd";
      import { useLongPress, useKeyPress, useEventListener } from "ahooks";
      const BackgroundAnimationMenu = ({
        currentBc,
        setCurrentBc,
        active,
        isOpen,
        setIsOpen,
      }) => {
        const menuList = ["Default", "Cycle", "Color Wheel", "Spotlight"];

        //"common_selected33333"
        return (
          <div
            class={`backgroundAnimationMenu_root ${
              active === 1 ? "common_selected" : ""
            }`}
          >
            <div
              class="backgroundAnimationMenu_btn"
              onClick={() => {
                setIsOpen(!isOpen);
              }}
            >
              <span class="back_btn_text">{currentBc}</span>
              <div class={isOpen ? "back_up" : "abck_down"} alt="" srcset="" />
            </div>

            {isOpen && (
              <div class="background_btn_list">
                {menuList?.map((_m, _index) => {
                  return (
                    <div
                      onClick={() => {
                        setCurrentBc(_m);
                      }}
                      key={_m}
                      class={`background_btn_list_item ${
                        _m === currentBc ? "active_btn" : ""
                      }`}
                    >
                      <span class="back_list_btn_text">{_m}</span>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        );
      };

      const HelloWorld = () => {
        const [currentBc, setCurrentBc] = React.useState("Default");

        const [isAsync, setIsAsync] = React.useState(false);

        // 划过选中的菜单
        const [active, setActive] = React.useState(3);

        // 当前进入的菜单
        const [currentMenuIndex, setCurrentMenuIndex] = React.useState(0);

        const list = ["Daily", "Weekly", "Monthly", "Quarterly", "Yearly"];

        // 是否高亮状态
        const [isHighLight, setIsHighLight] = React.useState(false);

        // 当前鼠标所在菜单项
        const [currentMenu, setCurrentMenu] = React.useState("Daily");

        // 当前亮度
        const [currentBrightness, setCurrentBrightness] = React.useState(0);

        // 获取设备的ipv4地址
        const [ipv4, setIpv4] = React.useState([
          "http://192.168.1.8:16021",
          "http://192.168.1.9:16021",
        ]);

        React.useEffect(() => {
          if (ipv4?.length > 0) {
            
          }
        }, [ipv4]);

        const [howD, setHowD] = React.useState(1);

        const remotePortRef = React.useRef();

        const localPortRef = React.useRef();

        // 扫描成功
        const [isScanSuccess, setIsScanSuccess] = React.useState(false);

        // 获取到屏幕的分辨率
        const [screenResolution, setScreenResolution] = React.useState({
          width: 0,
          height: 0,
        });

        function setupMessagePortAndGetDisplays(localPort) {
          var remotePort = tizen.messageport.requestRemoteMessagePort(
            remoteAppId,
            messagePortName,
            false
          );

          // Listen for the response from the remote application
          localPort.addMessagePortListener(function (data, remote) {
            //

            // 如果有返回值
            if (data && data.length > 0 && data[0].key === "response") {
              const response = JSON.parse(data[0].value);

              const { type = "", status = -2, result = [] } = response || {};

              displayResult(
                "结果2==>" +
                  JSON.stringify({
                    type,
                    result,
                  })
              );

              switch (type) {
                // 获取到getDisplays
                case "getDisplays":
                  if (status === 0) {
                    const displayInfo = response.result.displays[0];
                    const width = displayInfo.width;
                    const height = displayInfo.height;
                    setScreenResolution({
                      width: displayInfo.width,
                      height: displayInfo.height,
                    });

                    displayResult(
                      "Display Resolution:\n" + width + " x " + height
                    );
                  }
                  break;
                // 如果是开始扫描特定服务类型的设备。
                case "StartDeviceScan":
                  // 如果返回0，表示则表示扫描成功，开始需要通过GetDiscoveredServices返回已发现的服务列表。
                  if (status === -1) {
                    setIsScanSuccess(true);
                    displayResult("扫描成功");
                    setTimeout(() => {
                      remotePort.sendMessage(
                        [
                          {
                            key: "message",
                            value: JSON.stringify({
                              method: "GetDiscoveredServices",
                            }),
                          },
                        ],
                        localPort
                      );
                    }, 1000);
                  }

                  break;

                case "GetDiscoveredServices":
                  displayResult("返回所有设备");
                  const ipv4 = (response.result ?? [])?.map(
                    (_r) => `http://${_r?.IPv4Address}:${_r?.Port}`
                  );
                  setIpv4(Array.isArray(ipv4) ? ipv4 : [ipv4]);
                  displayResult(
                    "扫描到设备:\n" + Array.isArray(ipv4) ? ipv4 : [ipv4]
                  );
                  break;
                default:
                  break;
              }
            }
          });

          try {
            remotePort.sendMessage(
              [
                {
                  key: "message",
                  value: JSON.stringify({ method: "getDisplays" }),
                },
              ],
              localPort
            );

            remotePort.sendMessage(
              [
                {
                  key: "message",
                  value: JSON.stringify({
                    method: "StartDeviceScan",
                    serviceType: "_nanoleafapi._tcp",
                  }),
                },
              ],
              localPort
            );

            remotePortRef.current = remotePort;
            // displayResult("Sent display info request");
          } catch (error) {
            // displayResult("Failed to send request:\n" + error.message);
          }
        }

        function initializeService() {
          var maxRetries = 5;
          var retryCount = 0;
          var retryInterval = 2000; // 2 seconds

          function tryConnect() {
            try {
              var localPort = tizen.messageport.requestLocalMessagePort(
                messagePortName,
                false
              );

              localPortRef.current = localPort;

              try {
                setupMessagePortAndGetDisplays(localPort);
              } catch (error) {
                if (retryCount === 0) {
                  // First attempt failed, launch the service
                  // displayResult("Service not running\nLaunching service...");
                  tizen.application.launch(
                    remoteAppId,
                    function () {
                      // displayResult("Service launch initiated");
                      retryCount++;
                      // Wait and retry
                      setTimeout(tryConnect, retryInterval);
                    },
                    function (error) {
                      displayResult(
                        "Failed to launch service:\n" + error.message
                      );
                    }
                  );
                } else if (retryCount < maxRetries) {
                  // Service launched but not ready, retry
                  displayResult(
                    "Waiting for service... (Attempt " +
                      retryCount +
                      "/" +
                      maxRetries +
                      ")"
                  );
                  retryCount++;
                  setTimeout(tryConnect, retryInterval);
                } else {
                  displayResult(
                    "Service connection failed after " +
                      maxRetries +
                      " attempts"
                  );
                }
              }
            } catch (error) {
              displayResult("Failed to create MessagePort:\n" + error.message);
            }
          }

          tryConnect();
        }

        function displayResult(result) {
          // api.open({
          //   description: <Input.TextArea autoSize value={result} />,
          //   duration: null,
          // });
          // 在log_box后面添加元素
          const logBox = document.getElementById("log_box");
          const newElement = document.createElement("div");
          newElement.innerHTML = result;
          logBox.appendChild(newElement);
        }

        React.useEffect(() => {
          initializeService();
        }, []);

        //

        // 监听键盘按下事件，可以ahooks
        const [key, setKey] = React.useState("key");
        useKeyPress([37], (_event) => {
          if (isOpenAsyncSwitch || [1].includes(currentMenuIndex)) {
            return;
          }

          if ([5].includes(currentMenuIndex)) {
            if (howD === 1) {
              setHowD(4);
            } else {
              setHowD(howD - 1);
            }
            return;
          }
          if (active !== 1) {
            setActive(active - 1);
          }
        });

        // 监听鼠标右移动
        useKeyPress([39], (_event) => {
          if (isOpenAsyncSwitch || [1].includes(currentMenuIndex)) {
            return;
          }
          if ([5].includes(currentMenuIndex)) {
            if (howD === 4) {
              setHowD(1);
            } else {
              setHowD(howD + 1);
            }
            return;
          }
          if (active !== 5) {
            setActive(active + 1);
          }
        });

        // 监听鼠标上移动
        useKeyPress([38], (_event) => {
          if (isOpenAsyncSwitch) {
            setIsOpenAsyncSwitch(false);
          }

          // 当前确认进行亮度调整
          if (currentMenuIndex === 4) {
            if (currentBrightness < 100) {
              setCurrentBrightness(currentBrightness + 1);

              ipv4?.forEach((_ip) => {
                sendRequest(
                  `${_ip}/api/v1/jfH5xiUxkm7DXOchhogjfCw1JcoRnBLP/state`,
                  "PUT",
                  {
                    brightness: {
                      value: currentBrightness + 1,
                    },
                  }
                );
              });
            }
          }

          // 如果当前正在调整背景
          else if (currentMenuIndex === 1) {
            const menuList = ["Default", "Cycle", "Color Wheel", "Spotlight"];
            const _bcIndex = menuList.indexOf(currentBc);

            if (_bcIndex !== 0) {
              setCurrentBc(menuList[_bcIndex - 1]);
            }
          }
        });

        // 监听键盘下移动
        useKeyPress([40], (_event) => {
          // 当前确认进行亮度调整
          if (currentMenuIndex === 4) {
            if (currentBrightness > 0) {
              setCurrentBrightness(currentBrightness - 1);

              ipv4?.forEach((_ip) => {
                sendRequest(
                  `${_ip}/api/v1/jfH5xiUxkm7DXOchhogjfCw1JcoRnBLP/state`,
                  "PUT",
                  {
                    brightness: {
                      value: currentBrightness - 1,
                    },
                  }
                );
              });
            }
          } else if (currentMenuIndex === 3) {
            setIsOpenAsyncSwitch(true);
          }
          // 如果当前正在调整背景
          else if (currentMenuIndex === 1) {
            const menuList = ["Default", "Cycle", "Color Wheel", "Spotlight"];
            const _bcIndex = menuList.indexOf(currentBc);

            if (_bcIndex !== 3) {
              setCurrentBc(menuList[_bcIndex + 1]);
            }
          }
        });

        // 监听确定按钮
        useKeyPress([13], async (_event) => {
          if (active === 1) {
            setCurrentMenuIndex(active);
            if (isOpen) {
              setIsOpen(false);
              setCurrentMenuIndex(0);
            } else {
              setIsOpen(true);
            }
            return;
          }
          if (currentMenuIndex === 3 && isOpenAsyncSwitch) {
            setIsOpenAsyncSwitch(true);
            return setIsOpenAsync(!isOpenAsync);
          }
          if (active === 3) {
            setCurrentMenuIndex(active);

            const requests = ipv4?.map((_ip) => {
              return sendRequest(
                `${_ip}/api/v1/jfH5xiUxkm7DXOchhogjfCw1JcoRnBLP/state`,
                "PUT",
                {
                  on: {
                    value: !isHighLight,
                  },
                }
              ).catch((error) => {
                console.log("error", error);
                return null; // 或者你可以选择抛出错误，取决于你的需求
              });
            });

            Promise.all(requests)
              .then((results) => {
                // 处理所有请求的结果，results 是一个包含每个请求结果的数组
                console.log("All requests completed:", results);
              })
              .catch((error) => {
                // 处理所有请求中的错误
                console.log("Error in one of the requests:", error);
              });
            return setIsHighLight(!isHighLight);
          }

          if (currentMenuIndex === 1) {
            return setIsOpen(!isOpen);
          }

          if (currentMenuIndex === 0) {
            // 初次点击确认
            setCurrentMenuIndex(active);
          } else {
            setCurrentMenuIndex(0);
          }
        });

        const [isOpen, setIsOpen] = React.useState(false);

        const [enabled, setEnabled] = React.useState(true);

        // const [api, contextHolder] = notification.useNotification({
        //   stack: {
        //   threshold: 5,
        // }
        // });
        const [api, contextHolder] = notification.useNotification({
          stack: enabled
            ? {
                threshold: 3,
              }
            : false,
        });

        // 是否开启同步
        const [isOpenAsync, setIsOpenAsync] = React.useState(false);
        // 同步switch是否激活
        const [isOpenAsyncSwitch, setIsOpenAsyncSwitch] = React.useState(false);
        return (
          <div
            class={`project_root ${bcName[currentBc]} ${
              !isHighLight ? "bc5" : ""
            }`}
          >
            <BackgroundAnimationMenu
              currentBc={currentBc}
              setCurrentBc={setCurrentBc}
              active={active}
              setActive={setActive}
              isOpen={isOpen}
              setIsOpen={setIsOpen}
            />

            <div class="home_logo"></div>

            <div
              class={`home_setting ${active === 2 ? "common_selected" : ""}`}
            ></div>

            <div class="home_bottom">
              <div
                class={`home_bottom_left_01 ${!isHighLight ? "black_nc" : ""} ${
                  active === 3 ? "common_selected" : ""
                }`}
                onClick={(e) => {
                  // 阻止默认事件
                  e.preventDefault();
                  setIsHighLight(!isHighLight);

                  ipv4?.forEach((_ip) => {
                    sendRequest(
                      `${_ip}/api/v1/jfH5xiUxkm7DXOchhogjfCw1JcoRnBLP/state`,
                      "PUT",
                      {
                        on: {
                          value: !isHighLight,
                        },
                      }
                    );
                  });
                }}
                // 鼠标划过时
                onMouseOver={() => {
                  setCurrentMenu(1);
                }}
              >
                <div class="light_box" alt="" />
              </div>
              <div
                class={`${
                  isHighLight ? "autoAsyncBtn" : "autoAsyncBtnDisable"
                } ${isOpenAsyncSwitch ? "common_selected" : ""}`}
              >
                <span class="autoAsyncBtn_text">Auto Sync</span>

                <Switch
                  checked={isOpenAsync}
                  onChange={(e) => {
                    setIsOpenAsync(e.target.value);

                    // 启动镜像
                    remotePortRef?.current?.sendMessage(
                      [
                        {
                          key: "message",
                          value: JSON.stringify({
                            method: "startMirror",
                          }),
                        },
                      ],
                      localPortRef?.current
                    );
                  }}
                />
              </div>

              <div
                class={`home_bottom_left_02 ${
                  active === 4 ? "common_selected" : ""
                }`}
                onMouseOver={() => {
                  setCurrentMenu(2);
                }}
              >
                <div
                  class="proce_fill"
                  style={{
                    height: `${currentBrightness}%`,
                  }}
                ></div>

                <div class="light_png" alt="" />

                <div
                  class="light_up"
                  onClick={() => {
                    setCurrentBrightness(currentBrightness + 1);
                  }}
                ></div>

                <div
                  class="light_bottom"
                  onClick={() => {
                    setCurrentBrightness(currentBrightness - 1);
                  }}
                ></div>
              </div>

              <div
                onMouseOver={() => {
                  setCurrentMenu(3);
                }}
              >
                <Segmented
                  className={`type_segmented ${
                    active === 5 ? "type_segmented_hover" : ""
                  }`}
                  value={howD}
                  options={[
                    {
                      label: <div class="type_d one"></div>,
                      value: 1,
                    },
                    {
                      label: <div class="type_d two"></div>,
                      value: 2,
                    },
                    {
                      label: <div class="type_d three"></div>,
                      value: 3,
                    },
                    {
                      label: <div class="type_d four"></div>,
                      value: 4,
                    },
                  ]}
                />
              </div>
            </div>

            <div id="log_box"> </div>
          </div>
        );
      };

      ReactDOM.render(
        <div>
          <HelloWorld />
        </div>,
        document.getElementById("root")
      );
    </script>
  </body>
</html>
